package com.fablesoft.projectdatacollect.album;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import uk.co.senab.photoview.HackyViewPager;
import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener;

import com.fablesoft.projectdatacollect.R;
import com.fablesoft.projectdatacollect.ui.BaseRequestActivity;
import com.fablesoft.projectdatacollect.ui.PhotoActivity;
import com.fablesoft.projectdatacollect.util.Config;
import com.fablesoft.projectdatacollect.util.Log4jUtil;
import com.fablesoft.projectdatacollect.view.IndicatorView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;

/**
 * 这个是用于进行图片浏览时的界面
 *
 * @author king
 * @QQ:595163260
 * @version 2014年10月18日 下午11:47:53
 */
public class PreviewImageActivity extends BaseRequestActivity {
	// 返回按钮
	private LinearLayout back_bt;
	// 删除按钮
	private ImageView del_bt;
//	private TextView imageIndex;
	// 当前的位置
	private int location = 0;
	private ArrayList<View> listViews = null;
	private HackyViewPager pager;
	private MyPageAdapter adapter;
	RelativeLayout photo_relativeLayout;
	private int imageCount = 0;
	private IndicatorView indicator;
	private View headview;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
		setContentView(R.layout.preview_image);// 切屏到主界面
		back_bt = (LinearLayout) findViewById(R.id.gallery_back);
		del_bt = (ImageView) findViewById(R.id.gallery_del);
//		imageIndex = (TextView) findViewById(R.id.image_index);
		back_bt.setOnClickListener(new BackListener());
		del_bt.setOnClickListener(new DelListener());
		// 为发送按钮设置文字
		pager = (HackyViewPager) findViewById(R.id.gallery01);
		pager.setOnPageChangeListener(pageChangeListener);
		imageCount = PhotoActivity.imageList.size() - 1;
		for (int i = 0; i < imageCount; i++) {
			initListViews();
		}
		location = getIntent().getIntExtra("location", 0);
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		indicator = new IndicatorView(this);
		indicator.initIndicator(imageCount);
		params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		params.addRule(RelativeLayout.CENTER_HORIZONTAL);
		params.setMargins(0, 0, 0, getResources().getDimensionPixelOffset(
				R.dimen.ui_20_dip));
		indicator.setLayoutParams(params);
		if(indicator.getChildAt(location) != null){
			((RadioButton) indicator.getChildAt(location)).setChecked(true);
		}
		((ViewGroup)pager.getParent()).addView(indicator);
		
		adapter = new MyPageAdapter(listViews);
		pager.setAdapter(adapter);
		pager.setPageMargin(getResources().getDimensionPixelOffset(
				R.dimen.ui_5_dip));
		pager.setCurrentItem(location);
//		imageIndex.setText((location + 1) + "/" + imageCount);
		getWindow().clearFlags(
				WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		int result = 0;
		int resourceId = getResources().getIdentifier("status_bar_height",
				"dimen", "android");
		if (resourceId > 0) {
			result = getResources().getDimensionPixelSize(resourceId);
		}
		// int h =
		// Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 60,
		// getResources().getDisplayMetrics()));
		RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(
				LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);
		rl.setMargins(0, result, 0, 0);
		headview = findViewById(R.id.headview);
		headview.setLayoutParams(rl);
		headview.setVisibility(View.VISIBLE);
		this.setResult(Activity.RESULT_OK);
	}

	private OnPageChangeListener pageChangeListener = new OnPageChangeListener() {

		@Override
		public void onPageSelected(int arg0) {
			location = arg0;
			((RadioButton) indicator.getChildAt(location)).setChecked(true);
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}

		@Override
		public void onPageScrollStateChanged(int arg0) {

		}
	};

	private void initListViews() {
		if (listViews == null)
			listViews = new ArrayList<View>();
		PhotoView img = new PhotoView(this);
		img.setBackgroundColor(0xff000000);
		img.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT));
		img.setOnPhotoTapListener(new OnPhotoTapListener() {
			@Override
			public void onPhotoTap(View view, float x, float y) {
				if (headview.getVisibility() == View.VISIBLE) {
					headview.setVisibility(View.GONE);
					indicator.setVisibility(View.GONE);
				} else {
					headview.setVisibility(View.VISIBLE);
					indicator.setVisibility(View.VISIBLE);
				}
			}
		});
		listViews.add(img);
	}

	// 返回按钮添加的监听器
	private class BackListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			finish();
		}
	}

	// 删除按钮添加的监听器
	private class DelListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			createPromptDialog(PreviewImageActivity.this, null, getResources()
					.getString(R.string.delete_title), null, null,
					new ConfirmClickListener() {
						@Override
						public void confirmClickImp() {
							PhotoActivity.imageList
									.remove(location + 1);
							pager.removeAllViews();
							listViews.remove(location);
							if (listViews.size() == 0) {
								finish();
							} else {
								imageCount -= 1;
								indicator.initIndicator(imageCount);
								adapter.setListViews(listViews);
								adapter.notifyDataSetChanged();
							}
						}
					});
		}
	}

	/**
	 * 监听返回按钮
	 */
	// @Override
	// public boolean onKeyDown(int keyCode, KeyEvent event) {
	//
	// if (keyCode == KeyEvent.KEYCODE_BACK) {
	// finish();
	// }
	// return true;
	// }

	class MyPageAdapter extends PagerAdapter {
		DisplayImageOptions mOptions = new DisplayImageOptions.Builder()
				.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
				// .showImageOnLoading(R.drawable.plugin_camera_no_pictures)
				.resetViewBeforeLoading(true).cacheOnDisc(false)
				.bitmapConfig(Bitmap.Config.RGB_565).considerExifParams(true)
				.build();
		private ArrayList<View> listViews;

		private int size;

		public MyPageAdapter(ArrayList<View> listViews) {
			this.listViews = listViews;
			size = listViews == null ? 0 : listViews.size();
		}

		public void setListViews(ArrayList<View> listViews) {
			this.listViews = listViews;
			size = listViews == null ? 0 : listViews.size();
		}

		@Override
		public int getCount() {
			return size;
		}

		@Override
		public int getItemPosition(Object object) {
			return POSITION_NONE;
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((HackyViewPager) arg0).removeView(listViews.get(arg1 % size));
		}

		@Override
		public void finishUpdate(View arg0) {
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			ImageView imageView = (ImageView) listViews.get(arg1 % size);
			try {
				((HackyViewPager) arg0).addView(imageView, 0);

			} catch (Exception e) {
				Log4jUtil.e(e.toString());
			}
			Log.i("lzx", "arg1:" + arg1);
			Log.i("lzx", "size:" + size);
			Log.i("lzx", "location:" + arg1 % size);
			int position = arg1 % size;
			Map<String, String> imageInfo = (HashMap<String, String>) PhotoActivity.imageList
					.get(position + 1).getTag();
			String imagePath = imageInfo.get("localUri");
			ImageLoader.getInstance().displayImage(Config.BASE + imagePath,
					imageView, mOptions);
			return listViews.get(arg1 % size);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		// super.onRestoreInstanceState(savedInstanceState);
		finish();
	}
}
